package org.csu.mypetstore_seller.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_seller.domain.Item;
import org.csu.mypetstore_seller.domain.Product;
import org.csu.mypetstore_seller.persistence.ItemMapper;
import org.csu.mypetstore_seller.persistence.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.Objects;

@Controller
@Slf4j
@RequestMapping("catalog")
public class ItemController {
    @Autowired
    ProductMapper productMapper;  // 商品数据库接口

    @Autowired
    ItemMapper itemMapper;  // 库存项数据库接口

    @GetMapping("item*")
    private String item(@ModelAttribute Item item, Model model, HttpSession session){
        log.info("查看库存项详情，库存项ID：{}", item.getItemId());
        Item item1 = itemMapper.selectById(item.getItemId());
        Product product = productMapper.selectById(item1.getProductId());
        log.info("获取到商品信息，商品ID：{}", product.getProductId());

        // 传递数据到页面
        model.addAttribute("product",product);
        session.setAttribute("itemId",item1.getItemId());
        session.setAttribute("productId",product.getProductId());
        model.addAttribute("item",item1);
        return "catalog/item.html";
    }

    @GetMapping("appendNum*")
    private String appendItem(Model model, HttpSession session, WebRequest request){
        String resultNum = request.getParameter("resultNum");
        String itemId = (String)session.getAttribute("itemId");
        log.info("增加库存数量，库存项ID：{}，新数量：{}", itemId, resultNum);
        Item item = itemMapper.selectById(itemId);
        Product product = productMapper.selectById(item.getProductId());
        model.addAttribute("product",product);
        item.setAmount(Integer.parseInt(resultNum));
        model.addAttribute("item",item);
        itemMapper.updateById(item);
        return "catalog/item.html";
    }

//    @GetMapping("decreaseNum*")
//    private String decreaseNum(Model model, HttpSession session, WebRequest request){
//        String resultNum = request.getParameter("resultNum");
//        String itemId = (String)session.getAttribute("itemId");
//        log.info("减少库存数量，库存项ID：{}，新数量：{}", itemId, resultNum);
//        // 校验 resultNum 是否小于 0
//        int newAmount = Integer.parseInt(resultNum);
//
//            Item item = itemMapper.selectById(itemId);
//            Product product = productMapper.selectById(item.getProductId());
//            model.addAttribute("product",product);
//            item.setAmount(Integer.parseInt(resultNum));
//            model.addAttribute("item",item);
//            itemMapper.updateById(item);
//            return "catalog/item.html";
//
//
//    }

    @GetMapping("decreaseNum*")
    private String decreaseNum(Model model, HttpSession session, WebRequest request) {
        String resultNum = request.getParameter("resultNum");
        String itemId = (String) session.getAttribute("itemId");
        log.info("减少库存数量，库存项ID：{}，新数量：{}", itemId, resultNum);

//        try {
            // 校验 resultNum 是否为有效数字
            int newAmount = Integer.parseInt(resultNum);

            if (newAmount < 0) {
                // 如果 resultNum 小于 0，返回错误页面
                model.addAttribute("errorMessage", "库存数量不能为负数");
                return "catalog/error";
            } else {
                // 查询库存项和商品
                Item item = itemMapper.selectById(itemId);
                Product product = productMapper.selectById(item.getProductId());
                model.addAttribute("product", product);

                // 更新库存数量
                item.setAmount(newAmount);
                model.addAttribute("item", item);

                // 更新数据库
                itemMapper.updateById(item);

                // 返回库存页面
                return "catalog/item.html";
            }
//        } catch (NumberFormatException e) {
//            // 如果 resultNum 不是有效数字，返回错误页面
//            model.addAttribute("errorMessage", "请输入有效的库存数量");
//            return "catalog/error";
//        }
    }

    @GetMapping("deleteItem*")
    private String deleteItem(WebRequest request){
        String itemId = request.getParameter("itemId");
        log.info("删除库存项，库存项ID：{}", itemId);
        itemMapper.deleteById(itemId);
        return "catalog/afterDelete.html";
    }

    // 修改库存项详细信息
    @PostMapping("reviseItem*")
    private String reviseItem(WebRequest request){
        String itemId = request.getParameter("itemId");
        String productId = request.getParameter("productId");
        log.info("修改库存项信息，库存项ID：{}，商品ID：{}", itemId, productId);
        float listPrice = Float.parseFloat(Objects.requireNonNull(request.getParameter("listPrice").trim()));
        float unitCost = Float.parseFloat(Objects.requireNonNull(request.getParameter("unitCost").trim()));
        int supplier = Integer.parseInt(Objects.requireNonNull(request.getParameter("supplier")));
        String status = request.getParameter("status");
        String attr1 = request.getParameter("attr1");
        String attr2 = request.getParameter("attr2");
        String attr3 = request.getParameter("attr3");
        String attr4 = request.getParameter("attr4");
        String attr5 = request.getParameter("attr5");
        int amount = Integer.parseInt(request.getParameter("amount"));
        Item item = new Item();
        item.setItemId(itemId);
        item.setProductId(productId);
        item.setListPrice(BigDecimal.valueOf(listPrice));
        item.setUnitCost(BigDecimal.valueOf(unitCost));
        item.setSupplierId(supplier);
        item.setStatus(status);
        item.setAttribute1(attr1);
        item.setAttribute2(attr2);
        item.setAttribute3(attr3);
        item.setAttribute4(attr4);
        item.setAttribute5(attr5);
        item.setAmount(amount);
        itemMapper.updateById(item);
        log.info("库存项信息修改成功");
        return "catalog/afterRevise.html";
    }
}
